package com.zjhn.ds.netty;

import com.zjhn.ds.common.Constant;
import com.zjhn.ds.netty.handler.DeviceServerHandler;
import com.zjhn.ds.netty.handler.HtmlServerHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @BelongsProject: ds_jlw
 * @BelongsPackage: com.zjhn.ds.netty
 * @Author: sxt
 * @CreateTime: 2023-09-20  09:01
 * @Description:
 * @Version: 1.0
 */
@Slf4j
public class SocketChannelInitHandler extends ChannelInitializer<SocketChannel> {
    /**
     * 端口信息，用来区分这个端口属于哪种类型的连接 如：6001 属于 A
     */
    Map<Integer, String> ports;

    public SocketChannelInitHandler(Map<Integer, String> ports) {
        this.ports = ports;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //每次连接上来 对通道进行保存
        ChannelPipeline pipeline = socketChannel.pipeline();
        int port = socketChannel.localAddress().getPort();
        String type = ports.get(port);
        //不同类型连接，处理链中加入不同处理协议
        switch (type) {
            case Constant.NETTY_SERVER.DEVICE:
                // 设备
                pipeline.addLast(new DeviceServerHandler());
                break;
            case Constant.NETTY_SERVER.HTML:
                // HTML
                pipeline.addLast(new HtmlServerHandler());
                break;
            default:
                log.error("====[INFO]========SocketChannelInitHandler====initChannel 当前Netty端口类型并不存在于配置文件中，无法初始化通道");
                break;
        }
        pipeline.addLast(
                new StringEncoder(StandardCharsets.UTF_8),
                new StringDecoder(StandardCharsets.UTF_8));
    }
}
